%%--------------------------------------------------------------------
%% Author: <vjache>
%% Created: 17.03.2009
%% Description: This iterator has goal analoguos to lists:map. Its next()
%%				function takes item from underlying iterator (base iter) 
%%				applies	map function to this item and returns the 
%%				resulting one.
%%--------------------------------------------------------------------
-module(iter_mapper).

%%--------------------------------------------------------------------
%% Include files
%%--------------------------------------------------------------------
-include("../include/iter.hrl").
%%--------------------------------------------------------------------
%% Exported Functions
%%--------------------------------------------------------------------
-export([
		 new/2,
		 open/1,
		 next/1,
		 close/1,
		 test/1
		 ]).

%%--------------------------------------------------------------------
%% API Functions
%%--------------------------------------------------------------------

new(BaseIter,MapFun) 
	when is_record(BaseIter, iter) and is_function(MapFun, 1)->
	iter:from_module(
		?MODULE, 
		{BaseIter, MapFun}).

open({Iter,MapFun}) ->
	State=iter:open(Iter),
	{State,MapFun}.

next({State,MapFun}) ->
	{NewState,Item}=iter:next(State),
	case Item of
		?EOF ->
			{{NewState,MapFun},?EOF};
		_ ->
			case MapFun(Item) of
				?REJECT_REC -> 
					next({NewState,MapFun});
				MappedItem ->
					{{NewState,MapFun},MappedItem}
			end
	end.

close({State,_FilterPredFun}) ->
	ok=iter:close(State).

%%--------------------------------------------------------------------
%% Test Functions
%%--------------------------------------------------------------------

test(LL) ->
	I=iter:from_module(?MODULE, [iter:from_list(L)||L<-LL]),
	iter:foreach(I,fun(E)->
						   io:format("~p~n",[E])
				 end),
	ok.

%%--------------------------------------------------------------------
%% Local Functions
%%--------------------------------------------------------------------